package cn.edu.nju.software.zp13.assignment6.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.nju.software.zp13.assignment5.service.CourseScoreManager;
import cn.edu.nju.software.zp13.assignment5.service.soapMessage.CourseScoreListSOAPMsgProducer;
import cn.edu.nju.software.zp13.assignment5.service.soapMessage.SOAPMsgProducer;
import cn.edu.nju.software.zp13.assignment5.service.soapMessage.SOAPMsgWriter;
import cn.edu.nju.software.zp13.assignment6.service.soapMessage.IllegalUpdateSOAPMsgProducer;
import cn.edu.nju.software.zp13.client.assignment3.xmlNodeEntity.CourseScore;
import cn.edu.nju.software.zp13.client.assignment4.sax.CourseScoreSelector;
import cn.edu.nju.software.zp13.client.assignment4.sax.xmlNodeEntity.CourseScoreList;

/**
 * Servlet implementation class UpdateScore
 */
@WebServlet("/updateScore")
public class UpdateScore extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CourseScoreManager courseScoreManager;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UpdateScore() {
		super();
		courseScoreManager = new CourseScoreManager();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// resolve courseScoreList form request
		CourseScoreSelector selector = new CourseScoreSelector();
		CourseScore[] css = selector.selectRequiredCourseScore(s -> {
			return true;
		} , request.getInputStream());
		CourseScoreList courseScoreList = new CourseScoreList();
		courseScoreList.setCs(css);
		// update courseScore
		CourseScoreList updateResult = courseScoreManager.update(courseScoreList);
		// produce soap msg
		SOAPMsgProducer producer = null;
		if (updateResult == null) {
			producer = new IllegalUpdateSOAPMsgProducer();
		} else {
			producer = new CourseScoreListSOAPMsgProducer(updateResult);
		}
		SOAPMsgWriter.writeMsg(producer.produceSOAPMessage(), response.getOutputStream());
	}

}
